﻿using AutoMapper;
using MediatR;
using SC.GirdManage.Common;
using SC.GirdManage.Repository;
using SC.GridManage.API.Read.Application.command.PhysicalGrid;
using SC.GridManage.Domain.Models;
using System.Collections.Generic;

namespace SC.GridManage.API.Read.Application.handler.PhysicalGrid
{
    /// <summary>
    /// 中介者的Handler类,要实现IRequestHandler泛型接口 ,有in  out 两个泛型约束
    /// in:是我们定义的命令参数 out:是ApiResult包装的返回结果
    /// </summary>
    public class GetPhysicalGridListHandler : IRequestHandler<GetPhysicalGridListCommand, ApiResult<List<PhysicalGridDTO>>>
    {
        private readonly IBaseRepository<PhysicalGridModel> physicalGridRepo;
        private readonly ILogger<GetPhysicalGridListHandler> logger;
        private readonly IMapper mapper;

        public GetPhysicalGridListHandler(IBaseRepository<PhysicalGridModel> physicalGridRepo,
            ILogger<GetPhysicalGridListHandler> logger,
            IMapper mapper) {
            this.physicalGridRepo = physicalGridRepo;//仓储
            this.logger = logger;//日志
            this.mapper = mapper;//automapper
        }
        /// <summary>
        /// 中介者查询物理网格列表的处理方法
        /// </summary>
        /// <param name="request">参数,其中包含网格名称和区域名称</param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<ApiResult<List<PhysicalGridDTO>>> Handle(GetPhysicalGridListCommand request, CancellationToken cancellationToken)
        {
            //申明一个ApiRulst
            ApiResult<List<PhysicalGridDTO>> result = new ApiResult<List<PhysicalGridDTO>>();
            try
            {

                var gridquery = physicalGridRepo.QueryAsync().Result.Where(x=>x.IsDeleted==false);//直接使用仓储查询物理网格,返回的是查询表达式
                if (!string.IsNullOrEmpty(request.GridName))//判断是否要加入GridName这个过滤条件
                {
                    gridquery = gridquery.Where(x => x.GridName.Contains(request.GridName));
                }
                //AutoMapper 
                result.Data = mapper.Map<List<PhysicalGridDTO>>(gridquery.ToList());
                result.Msg = "查询成功!";
                result.Code= GirdManage.Common.Enums.EnumResultCode.Success;
            }
            catch (Exception)
            {

                //result.Data = null;
                result.Msg = "查询失败!";
                result.Code = GirdManage.Common.Enums.EnumResultCode.Fail;
            }
            return Task.FromResult(result);
        }
    }
}
